package com.wuhunyu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.wuhunyu.commonutils.check.Check;
import com.wuhunyu.commonutils.check.EmailCheckUtil;
import com.wuhunyu.commonutils.check.PhoneCheckUtil;
import com.wuhunyu.commonutils.check.RandomUtil;
import com.wuhunyu.commonutils.result.CommonResult;
import com.wuhunyu.service.MsmService;
import com.wuhunyu.servicebase.exception.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务实现类
 *
 * @author wuhunyu
 * @version 1.0
 * @date 2021-01-22 21:06
 */
@Service("msmService")
public class MsmServiceImpl implements MsmService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发件人邮箱
     */
    @Value("${spring.mail.username}")
    private String sendEmail;

    /**
     * 邮件标题
     */
    @Value("${spring.mail.title}")
    private String title;

    @Override
    public CommonResult sendPhone(String phone) {
        // 判断在事件范围内是否存在短信验证码
        String msg = redisTemplate.opsForValue().get(phone);
        if (Check.isBlank(msg)) {
            // 封装数据
            HashMap<String, Object> result = new HashMap<>(16);
            result.put("msg", msg);
            return CommonResult.success("短信验证码已发送", result);
        }
        // 生成六位随机手机验证码
        String code = RandomUtil.getSixBitRandom();
        // 封装验证码
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("code", code);
        // 校验手机号
        Assert.isRight(!PhoneCheckUtil.isPhone(phone), "手机号码合适错误");
        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI4Fz6X1jmbT8XksaBc1Lq", "b5y3VrY6tUVYxqaKKSWbXGCbR5Spqi");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        // 短信提交方式
        request.setSysMethod(MethodType.POST);
        // 调用服务器端
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        // 设置发送相关参数
        // 手机号
        request.putQueryParameter("PhoneNumbers", phone);
        // 申请的服务名
        request.putQueryParameter("SignName", "无魂雨客户管理管理系统");
        // 验证码
        request.putQueryParameter("TemplateCode", code);
        // 验证码
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
            // 判断是否成功
            Assert.isRight(!response.getHttpResponse().isSuccess(), "短信验证码发送失败");
            // 将验证码添加到redis中，设置时长是5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        } catch (ClientException e) {
            Assert.isRight(true, e.getMessage());
        }
        return CommonResult.success("短信验证码发送成功");
    }

    @Override
    public CommonResult sendEmail(String email) {
        // 校验邮件
        Assert.isRight(!EmailCheckUtil.isEmail(email), "邮件格式有误");
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper minehelper = new MimeMessageHelper(message, true);
            // 发件人地址
            minehelper.setFrom(sendEmail);
            // 收件人地址
            minehelper.setTo(email);
            //邮件标题
            minehelper.setSubject(title);
            // 生成六位随机手机验证码
            String code = RandomUtil.getSixBitRandom();
            //邮件内容
            String content = "您的登录验证码为：<span style='color: orange; text-decoration: underline'>" + code + "</span>，该验证码5分钟内有效，请勿泄露于其他人";
            minehelper.setText(content, true);
            mailSender.send(message);
            // 将验证码添加到redis中，设置时长是5分钟
            redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
        } catch (MessagingException e) {
            Assert.isRight(false, "邮件发送失败:" + e.getMessage());
        }
        return CommonResult.success("邮件验证码发送成功");
    }
}
